﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Authorization; 
using Microsoft.AspNetCore.Mvc.Controllers; 
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Api.Swagger
{
    public class AddAuthTokenHeaderParameter : IOperationFilter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="context"></param>
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null) operation.Parameters = new List<IParameter>();
            var attrs = context.ApiDescription.ActionDescriptor.AttributeRouteInfo;

            //先判断是否是匿名访问,
            var descriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;
            if (descriptor != null)
            {
                var actionAttributes = descriptor.MethodInfo.GetCustomAttributes(inherit: true);
                bool isAnonymous = actionAttributes.Any(a => a is AllowAnonymousAttribute);
                //非匿名的方法,链接中添加accesstoken值
                if (!isAnonymous)
                {
                    operation.Parameters.Add(new NonBodyParameter()
                    {
                        Name = "token",
                        In = "query",//query header body path formData
                        Type = "string",
                        Required = true, //是否必选
                        Default = "eyJ0cCI6Ik1ENSJ9.eyJpc3MiOiJzaWduQnkiLCJqdGkiOiI0OTgzYTI2OC0yYTQyLTRlOTItOTQ0ZS05OTU0MGEzZWYxNTciLCJleHAiOiIyMDIwLTEwLTI5VDA5OjU5OjU0LjgyNTE0NTQrMDg6MDAiLCJuYmYiOiIyMDIwLTEwLTIyVDA5OjU5OjU0LjgyNTE0NzIrMDg6MDAiLCJpYXQiOiIyMDIwLTEwLTIyVDA5OjU5OjU0LjgyNTE0ODcrMDg6MDAiLCJzdWIiOiJzdWJqZWN0IiwiYXVkIjoiYXVkaWVuY2UiLCJ0b2tlbnVzZXIiOnsidWlkIjoiNCIsImxvZ2luX25hbWUiOiIxMzgyMDg3OTE1MyIsInVfbmFtZSI6Ik0iLCJsb2dpbl9wd2QiOiIwNGQ3YmIxYWE2NDJlNzFhNzdiODUyYTk4OTNmNmVmYSIsImFk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